<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="imgSrc" v-if="imgSrc" alt="" class="preview" />
      <img src="../../../assets/images/avatar.jpg" v-else alt="" class="preview" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" style="display:none" ref="inputImg" @change="chooseImg">
        <el-button type="primary" icon="el-icon-plus" @click="$refs.inputImg.click()">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="imgSrc===''" @click="upImg">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      imgSrc:'',
    }
  },
  methods:{
    chooseImg(e){
      if(!e.target.files.length) return this.imgSrc=''
        //上传成功
      let reader  = new FileReader();
        reader.readAsDataURL(e.target.files[0]);
        reader.addEventListener("load", ()=> {
          // console.log(reader);
          this.imgSrc = reader.result;
      }, false);
      // console.log(e);
    },
    async upImg(){
     const res = await this.$http.patch('/my/update/avatar',{avatar:this.imgSrc})
     this.imgSrc=''
     this.$store.dispatch('getUser')
    //  console.log(res);
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
